/*
 * CSelectUtils.cpp
 *
 *  Created on: 2011-9-10
 *      Author: stargui
 */

#include "CPSelectUtils.h"

CPSelectUtils::CPSelectUtils()
{
	_maxhandle = -1;
	FD_ZERO(&_sets[P_FD_SETS_READ]);
	FD_ZERO(&_sets[P_FD_SETS_WRITE]);
	FD_ZERO(&_sets[P_FD_SETS_ERROR]);
}

CPSelectUtils::~CPSelectUtils()
{

}

int CPSelectUtils::InsertfdSets(int fd, P_FD_SETS_ENUMS sets)
{
	if(fd > 0)
	{
		FD_SET(fd, &_sets[sets]);
		if (fd > _maxhandle)
		{
			_maxhandle = fd;
		}
	}
	return _maxhandle;
}

bool CPSelectUtils::CheckSets(int fd, P_FD_SETS_ENUMS sets)
{
	if(fd <= 0)
	{
		return false;
	}
	return (FD_ISSET(fd, &_sets[sets]));
}

int CPSelectUtils::Select( int selectSec, int selectUsec)
{
	struct timeval tv;
	tv.tv_sec = selectSec / 1000000;
	tv.tv_usec = selectUsec % 1000000;
	return select(_maxhandle + 1, &_sets[P_FD_SETS_READ], &_sets[P_FD_SETS_WRITE], &_sets[P_FD_SETS_ERROR], &tv);
}

void CPSelectUtils::mSleep(unsigned int  MilliSecond)
{
	struct timeval time;

	time.tv_sec = MilliSecond / 1000;//seconds
	time.tv_usec = MilliSecond * 1000 % 1000000;//microsecond

	select(0, NULL, NULL, NULL, &time);
}
